package com.baizhi.mall.service.impl;

import com.baizhi.mall.entity.mysql.BzCategoryDO;
import com.baizhi.mall.mapper.BzCategoryMapper;
import com.baizhi.mall.service.IBzCategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品三级分类 服务实现类
 * </p>
 *
 * @author zhw
 * @since 2021-05-17
 */
@Service
public class BzCategoryServiceImpl extends ServiceImpl<BzCategoryMapper, BzCategoryDO> implements IBzCategoryService {
    @Autowired
    private BzCategoryMapper cm;
    @Override
    public PageInfo<BzCategoryDO> selectByPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<BzCategoryDO> list=cm.selectList(null);
        PageInfo<BzCategoryDO> info=new PageInfo<>(list);
        return info;
    }

    @Override
    public List<BzCategoryDO> selectAll(Integer parentId) {
        QueryWrapper<BzCategoryDO> wrapper=new QueryWrapper<>();
        wrapper.eq("parent_id",parentId);
        List<BzCategoryDO>list=cm.selectList(wrapper);
        return list;
    }

    @Override
    public List<BzCategoryDO> selectTree() {
        List<BzCategoryDO>list=cm.selectList(null);//简单地从数据库把数据全部查询出来，查出所有菜单，包括1级，2级和三级
        List<BzCategoryDO> collect=list.stream()
                .filter((category)->category.getParentId()==0)//过滤出一级分类信息
                .peek((category)->category.setCategoryList(getChildrenMenu(category.getCategoryId(),list)))//同时给一级分类的children属性赋值。
                .collect(Collectors.toList());
        return collect;
    }
    private List<BzCategoryDO> getChildrenMenu(int parenId, List<BzCategoryDO> categorys){
        return categorys.stream()
                .filter(category->category.getParentId()==parenId)
                .peek(category->category.setCategoryList(getChildrenMenu(category.getCategoryId(),categorys)))
                .collect(Collectors.toList());
    }

    @Override
    public void insert(BzCategoryDO category) {
        cm.insert(category);
    }

    @Override
    public void delete(Integer id) {
        cm.deleteById(id);
    }

    @Override
    public void update(BzCategoryDO category) {
        cm.updateById(category);
    }

    @Override
    public void updateStatus(Integer showStatus, Integer categoryId) {
        cm.updateStatus(showStatus,categoryId);
    }
}
